<template>
  <div id="MessagePage">
    <el-container>
      <el-header>
        <h1>收到的信息列表</h1>
      </el-header>
      <el-main>
        <el-row align="middle">
          <span style="margin-left: 2.5%; margin-right: 1%;">筛选发信人: </span>
          <el-select v-model="selectedSender" style="width:10%" @change="handleSenderChange">
            <el-option
                v-for="option in senders"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
          <span style="margin-left: 14.3%; margin-right: 1%">筛选标题: </span>
          <el-select v-model="selectedTitle" style="width:10%" @change="handleTitleChange">
            <el-option
                v-for="option in titles"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
          <span style="margin-left:15.5%; margin-right: 1%;">筛选日期: </span>
          <el-select v-model="selectedDate" style="width:10%" @change="handleDateChange">
            <el-option
                v-for="option in dates"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-row>
        <el-table :data="messages" height="60vh" border @selection-change="handleSelectionChange" style="margin-top: 1%">
          <el-table-column fixed type="selection" width="37%" />
          <el-table-column prop="sender" label="发信人" />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="date" label="日期" />
          <el-table-column fixed="right" label="操作" width="100%">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleRowClick(scope.row)">详情</el-button>
              <el-button link type="primary" size="small" @click="deleteMessage(scope.row)" style="color: rgba(255,0,0,0.82)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 3%" align="middle" justify="center">
          <el-button type="primary" class="custom-button" style="background: #0674e0;border: none; margin-right: 15%;" v-on:click="createMessage" >新建信息</el-button>
          <el-button type="primary" class="custom-button" style="background: #e01b2b;border: none" v-on:click="deleteMessages">删除信息</el-button>
        </el-row>
      </el-main>
    </el-container>
    <el-dialog v-model="dialogVisible" :style="{height: '60vh'}" title="信息内容" width="60%" draggable overflow>
      <div class="dialog-content-right">
        <p><strong>发信人:</strong> {{ selectedMessage.sender }}</p>
        <p><strong>标题:</strong> {{ selectedMessage.title }}</p>
        <p><strong>日期:</strong> {{ selectedMessage.date }}</p>
        <p><strong>内容:</strong></p>
        <div >{{ selectedMessage.content }}</div>
      </div>
    </el-dialog>
    <el-dialog v-model="messageVisible" :style="{height: '60vh'}" title="新建信息" width="60%" draggable overflow :before-close="closeDialog">
      <div class="dialog-content-right">
        <p><strong>收信人:</strong> <el-input v-model="newMessage.receiver"></el-input></p>
        <p><strong>标题:</strong><el-input v-model="newMessage.title"></el-input></p>
        <p><strong>内容:</strong><el-input type="textarea" v-model="newMessage.content" :style="{ textAlign: 'left' } " :autosize="{ minRows: 14}"></el-input></p>
      </div>
      <el-row style="margin-top: 3%" align="middle" justify="center">
        <el-button type="primary" class="custom-button" style="background: #0674e0;border: none; margin-right: 15%;" v-on:click="saveDraft" >保存草稿</el-button>
        <el-button type="primary" class="custom-button" style="background: #0674e0;border: none" v-on:click="sendMessage">发送信息</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {onMounted, reactive, ref, toRefs, watch} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import store from "@/store";

export default {
  name: 'MessagePage',
  setup() {
    const currentUser = reactive(toRefs(store.state.currentUser));
    let newMessage = reactive({
      receiver: '',
      title: '',
      content: '',
      sender: store.state.id,
      date: ''
    });
    const messages = ref([]);
    const senders = ref([]);
    const titles = ref([]);
    const dates = ref([]);

    const dialogVisible = ref(false);
    const messageVisible = ref(false);
    const save = ref(false);
    const selectedMessage = ref({});
    const selectedSender = ref("所有");
    const selectedDate = ref("所有");
    const selectedTitle = ref("所有");
    const selectedRows = ref([])

    watch(newMessage, () => {
      save.value = false;
    }, { deep: true });

    onMounted(() => {
      fetchDataFromDatabase(1);
    });

    const fetchDataFromDatabase = (i) => {
      const data = {
        sender: selectedSender.value,
        title: selectedTitle.value,
        date: selectedDate.value,
        receiver: store.state.id
        
      };
      axios.post('http://localhost:8085/messages', data)  //通过data中的四个是否为全部来判断是否进行筛选
          .then(response => {
            if (response.status === 200) {
              messages.value = response.data
              if(i){
                const uniqueSenders1 = Array.from(new Set(messages.value.map(msg => msg.sender)));
                senders.value = uniqueSenders1.map(sender => ({ label: sender, value: sender }));
                senders.value.unshift({ label: "所有", value: "所有" });
                const uniqueSenders2 = Array.from(new Set(messages.value.map(msg => msg.title)));
                titles.value = uniqueSenders2.map(title => ({ label: title, value: title }));
                titles.value.unshift({ label: "所有", value: "所有" });
                const uniqueSenders3 = Array.from(new Set(messages.value.map(msg => msg.date.substring(0, 10))));
                dates.value = uniqueSenders3.map(date => ({ label: date, value: date }));
                dates.value.unshift({ label: "所有", value: "所有" });
              }
              ElMessage({
                type: 'success',
                message: '载入数据成功',
              });
            } else {
              ElMessage({
                type: 'error',
                message: '载入数据失败，请重试',
              });
            }
          })
          .catch((error) => {
            console.error('Error updating user information:', error);
            ElMessage({
              type: 'error',
              message: '载入数据失败，请重试',
            });
          });
    };

    const handleRowClick = (row) => {
      selectedMessage.value = row;
      dialogVisible.value = true;
    };

    const deleteMessage = (row) => {
      ElMessageBox.confirm(
          '确认删除所选信息？',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            let ids = [row.id]
            axios.post(`http://localhost:8085/messages/delete`, ids)
                .then(response => {
                  if (response.status === 200) {
                    fetchDataFromDatabase(1);
                    ElMessage({
                      type: 'success',
                      message: '删除成功',
                    });
                  } else {
                    ElMessage({
                      type: 'error',
                      message: '删除失败，请重试',
                    });
                  }
                })
                .catch((error) => {
                  console.error('Error updating user information:', error);
                  ElMessage({
                    type: 'error',
                    message: '删除失败，请重试',
                  });
                });
          })
          .catch(err => {
            console.error('Error updating user information:', err);
            ElMessage({
              type: 'info',
              message: '删除操作已取消',
            })
          })
    };

    const handleDialogClose = () => {
      dialogVisible.value = false;
    };

    const handleSenderChange = (sender) => {
      selectedSender.value = sender;
      fetchDataFromDatabase(0);
    }

    const handleDateChange = (date) => {
      selectedDate.value = date;
      fetchDataFromDatabase(0);
    }

    const handleTitleChange = (title) => {
      selectedTitle.value = title;
      fetchDataFromDatabase(0);
    }

    const handleSelectionChange = (row) => {
      selectedRows.value = row;
    }

    const createMessage = () => {
      messageVisible.value = true;
      save.value = false;
    }

    const deleteMessages = () => {
      ElMessageBox.confirm(
          '确认删除所选信息？',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            //在这里，将selectedRows转换为合适的数据传给后段
            let ids = selectedRows.value.map(item => item.id);
            axios.post(`http://localhost:8085/messages/delete`, ids)
                .then(response => {
                  if (response.status === 200) {
                    fetchDataFromDatabase(1);
                    ElMessage({
                      type: 'success',
                      message: '删除成功',
                    });
                  } else {
                    ElMessage({
                      type: 'error',
                      message: '删除失败，请重试',
                    });
                  }
                })
                .catch((error) => {
                  console.error('Error updating user information:', error);
                  ElMessage({
                    type: 'error',
                    message: '删除失败，请重试',
                  });
                });
          })
          .catch(err => {
            console.error('Error updating user information:', err);
            ElMessage({
              type: 'info',
              message: '删除操作已取消',
            })
          })
      // confirmed.value = true;
    }

    const closeDialog = () => {
      ElMessageBox.confirm(
          '请确保草稿已保存。确认退出？',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            messageVisible.value = false;
            if(!save.value){
              refresh();
            }
          })
          .catch(err => {
            console.error('Error updating user information:', err);
            ElMessage({
              type: 'info',
              message: '退出操作已取消',
            })
          })
    }

    const refresh = () => {
      newMessage.content = '';
      newMessage.receiver = '';
      newMessage.title = '';
    }

    const saveDraft = () => {
      save.value = true
    }

    const sendMessage = () => {
      ElMessageBox.confirm(
          '确认发送？',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            const currentDate = new Date().toISOString();
            newMessage.date = currentDate.substring(0, 10) + ' ' + currentDate.substring(11, 19);
            axios.post(`http://localhost:8085/messages/add`, newMessage)
                .then(response => {
                  if (response.status === 200) {
                    refresh();
                    messageVisible.value = false;
                    fetchDataFromDatabase(1);
                    ElMessage({
                      type: 'success',
                      message: '发送成功',
                    });
                  } else {  //这里可以根据返回code值的不同判断错误类型，从而进行个性化错误输出
                    ElMessage({
                      type: 'error',
                      message: '发送失败，请重试',
                    });
                  }
                })
                .catch((error) => {
                  console.error('Error updating user information:', error);
                  ElMessage({
                    type: 'error',
                    message: '发送失败，请重试',
                  });
                  // console.error('Error updating user information:', error);
                });
          })
          .catch(err => {
            console.error('Error updating user information:', err);
            ElMessage({
              type: 'info',
              message: '发送已取消',
            })
          })
    }

    return {
      messages,
      dialogVisible,
      selectedMessage,
      selectedDate,
      selectedTitle,
      handleRowClick,
      handleDialogClose,
      handleSelectionChange,
      selectedSender,
      senders,
      titles,
      dates,
      handleSenderChange,
      handleTitleChange,
      handleDateChange,
      createMessage,
      deleteMessages,
      messageVisible,
      newMessage,
      closeDialog,
      saveDraft,
      sendMessage,
      deleteMessage
    };
  },
};
</script>

<style scoped>
#MessagePage {
  padding: 20px;
}

.dialog-content-right {
  text-align: left;
}

</style>